package com.sunshine.wrongquestionset.room.repository

import android.content.Context
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.room.Query
import com.sunshine.wrongquestionset.room.dao.*
import com.sunshine.wrongquestionset.room.database.MyDatabase
import com.sunshine.wrongquestionset.room.entity.*
import java.util.*
import kotlin.collections.ArrayList

/**
 * @author sunshine
 * @date 2021/3/26
 */
class MyRepository(context: Context) {
    private val appConfigDao: AppConfigDao
    private val questionDao: QuestionDao
    private val questionSetDao: QuestionSetDao
    private val questionTypeDao: QuestionTypeDao
    private val subjectDao: SubjectDao
    private val userDao: UserDao
    private val wrongQuestionDao: WrongQuestionDao
    private val questionInfoDao: QuestionInfoDao

    //配置的增删查改
    fun insertAppConfig(appConfigEntity: AppConfigEntity) {
        appConfigDao.insert(appConfigEntity)
    }

    fun deleteAppConfig(appConfigEntity: AppConfigEntity) {
        appConfigDao.delete(appConfigEntity)
    }

    fun getAppConfig(id: String): LiveData<AppConfigEntity> {
        return appConfigDao.select(id)
    }

    //判断是否有登录用户
    fun hasLoginUser(): Boolean {
        return appConfigDao.hasLoginUserCount() > 0
    }

    fun getLoginUserId(): LiveData<String?> {
        return appConfigDao.getLoginUserId()
    }

    fun updateAppConfigByEntity(appConfigEntity: AppConfigEntity) {
        appConfigDao.updateByEntity(appConfigEntity)
    }

    fun updateAppConfig(userId: String, isLogin: Boolean) {
        appConfigDao.update(userId, isLogin)
    }

//    //更新当前用户的错题集id
//    fun updateQuestionSetId(id: String, nowQuestionSetId: Int) {
//        appConfigDao.updateQuestionSetId(id, nowQuestionSetId)
//    }

    //问题的增删查改
    fun insertQuestion(
        userId: String,
        questionSetId: Int,
        subjectId: Int,
        typeId: Int,
        tag: String,
        titlePath: String,
        answerPath: String,
        familiarity: Float,
        difficulty: Float,
        lastTime: Long,
        doCount: Int,
        note: String?,
        insertTime: Long,
        score: Float
    ) {
        questionDao.insert(userId, questionSetId, subjectId, typeId, tag, titlePath, answerPath, familiarity, difficulty, lastTime, doCount, note, insertTime, score)
    }

    fun deleteQuestionByEntity(questionEntity: QuestionEntity) {
        questionDao.deleteByEntity(questionEntity)
    }

//    fun deleteQuestionByFamiliarity(userId: String, familiarity: Float) {
//        questionDao.deleteByFamiliarity(userId, familiarity)
//    }
//
//    fun deleteQuestionByFamiliarityAndSetId(questionSetId: Int, familiarity: Float) {
//        questionDao.deleteByFamiliarityAndSetId(questionSetId, familiarity)
//    }

    fun deleteAllQuestion(userId: String) {
        questionDao.deleteAll(userId)
    }

    fun deleteAllInSetId(questionSetId: Int) {
        questionDao.deleteAllInSetId(questionSetId)
    }

    fun getAllQuestion(): LiveData<List<QuestionEntity>?> {
        return questionDao.selectAll()
    }

    fun getQuestionById(questionId: Int): LiveData<QuestionEntity?> {
        return questionDao.selectById(questionId)
    }

    fun getAllQuestionInSetId(questionSetId: Int): LiveData<List<QuestionEntity>?> {
        return questionDao.selectAllInSetId(questionSetId)
    }

    fun getUserAllQuestion(userId: String): LiveData<List<QuestionEntity>?> {
        return questionDao.selectUserAll(userId)
    }

    fun getQuestionBySubject(subjectId: Int): LiveData<List<QuestionEntity>?> {
        return questionDao.selectBySubject(subjectId)
    }

//    //查询某用户某科目下的所有错题
//    fun getQuestionBySubject(owner: LifecycleOwner, userId: String, subjectId: Int): LiveData<List<QuestionEntity>?> {
//        val list = MutableLiveData<List<QuestionEntity>?>()
//        //新建一个缓存列表
//        var tempQuestionList = ArrayList<QuestionEntity>()
//
//        getIdBySubjectId(userId, subjectId).observe(owner, Observer {questionSetList ->
//            //列表为空，更新list
//            if (questionSetList == null) list.value = tempQuestionList
//            else {
//
////                //本次是否更新过
////                var isAdd = false
//                questionSetList.forEach { questionSetId ->
//                    getAllQuestionInSetId(questionSetId).observe(owner, Observer {questionEntityList ->
//                        //list.postValue(questionEntityList)
//                        questionEntityList?.forEach {
//                            tempQuestionList.add(it)
////                            //刷新更新过状态
////                            isAdd = true
//                        }
//
//                        //更新返回列表
//                        list.value = tempQuestionList
////                        else list.postValue(null)
////
////                        //等待下一次更新
////                        isAdd = false
//
//                    })
//                }
//            }
//        })
//        return list
//    }

//    fun getQuestionBySubjectAndSetId(questionSetId: Int, subjectId: Int): LiveData<List<QuestionEntity>?> {
//        return questionDao.selectBySubjectAndSetId(questionSetId, subjectId)
//    }

    fun getQuestionByType(userId: String, typeId: Int): LiveData<List<QuestionEntity>?> {
        return questionDao.selectByType(userId, typeId)
    }

    fun getQuestionByTypeAndSetId(questionSetId: Int, typeId: Int): LiveData<List<QuestionEntity>?> {
        return questionDao.selectByTypeAndSetId(questionSetId, typeId)
    }

//    fun getQuestionByGreaterFamiliarity(userId: String, familiarity: Float): LiveData<List<QuestionEntity>?> {
//        return questionDao.selectByGreaterFamiliarity(userId, familiarity)
//    }
//
//    fun getQuestionByGreaterFamiliarityAndSetId(questionSetId: Int, familiarity: Float): LiveData<List<QuestionEntity>?> {
//        return questionDao.selectByGreaterFamiliarityAndSetId(questionSetId, familiarity)
//    }
//
//    fun getQuestionByLessFamiliarity(userId: String, familiarity: Float): LiveData<List<QuestionEntity>?> {
//        return questionDao.selectByLessFamiliarity(userId, familiarity)
//    }
//
//    fun getQuestionByLessFamiliarityAndSetId(questionSetId: Int, familiarity: Float): LiveData<List<QuestionEntity>?> {
//        return questionDao.selectByLessFamiliarityAndSetId(questionSetId, familiarity)
//    }

    fun getQuestionByGreaterDifficulty(userId: String, difficulty: Float): LiveData<List<QuestionEntity>?> {
        return questionDao.selectByGreaterDifficulty(userId, difficulty)
    }

    fun getQuestionByGreaterDifficultyAndSetId(questionSetId: Int, difficulty: Float): LiveData<List<QuestionEntity>?> {
        return questionDao.selectByGreaterDifficultyAndSetId(questionSetId, difficulty)
    }

    fun getQuestionByLessDifficulty(userId: String, difficulty: Float): LiveData<List<QuestionEntity>?> {
        return questionDao.selectByLessDifficulty(userId, difficulty)
    }

    fun getLastQuestion(): LiveData<QuestionEntity> {
        return questionDao.selectLastQuestion()
    }

    fun getQuestionByLessDifficultyAndSetId(questionSetId: Int, difficulty: Float): LiveData<List<QuestionEntity>?> {
        return questionDao.selectByLessDifficultyAndSetId(questionSetId, difficulty)
    }

    fun getQuestionCountInSetId(setId: Int): LiveData<Int> {
        return questionDao.selectQuestionCountInSetId(setId)
    }

    fun updateQuestionByEntity(questionEntity: QuestionEntity) {
        questionDao.updateByEntity(questionEntity)
    }

    //因为题目的熟悉程度需要经常更新，所以有一个更新熟悉程度的sql
    fun updateQuestionFamiliarity(id: Int, familiarity: Float) {
        questionDao.updateFamiliarity(id, familiarity)
    }

    //错题集的增删查改
    fun insertQuestionSet(userId: String, name: String, description: String?, subjectId: Int, backgroundColor: String) {
        questionSetDao.insert(userId, name, description, subjectId, backgroundColor)
    }

    fun insertQuestionSetByEntity(questionSetEntity: QuestionSetEntity) {
        questionSetDao.insertByEntity(questionSetEntity)
    }

    //不允许删除默认的表
    fun deleteQuestionSet(questionSetEntity: QuestionSetEntity): Boolean {
        //if (questionSetEntity.isDefault) return false
        questionSetDao.delete(questionSetEntity)
        return true
    }

    fun getQuestionSetByUserId(userId: String): LiveData<List<QuestionSetEntity>?> {
        return questionSetDao.selectByUserId(userId)
    }

    fun getQuestionSetBySubjectId(userId: String, subjectId: Int): LiveData<List<QuestionSetEntity>?> {
        return questionSetDao.selectBySubjectId(userId, subjectId)
    }

    fun getIdBySubjectId(userId: String, subjectId: Int): LiveData<List<Int>?> {
        return questionSetDao.selectIdBySubjectId(userId, subjectId)
    }

    fun getQuestionSetCountInSubjectId(subjectId: Int): LiveData<Int> {
        return questionSetDao.selectCountInSubjectId(subjectId)
    }

    fun getQuestionSetActivityBeanList(userId: String): LiveData<List<QuestionSetActivityBean>?>{
        return questionSetDao.selectQuestionSetActivityBeanList(userId)
    }

    fun getQuestionSetActivityBeanListBySubjectId(userId: String, subjectId: Int): LiveData<List<QuestionSetActivityBean>?> {
        return questionSetDao.selectQuestionSetActivityBeanListBySubjectId(userId, subjectId)
    }

    fun updateQuestionSet(questionSetEntity: QuestionSetEntity) {
        questionSetDao.update(questionSetEntity)
    }

    //题目类型的增删查改
    fun insertQuestionType(name: String) {
        questionTypeDao.insert(name)
    }

    fun insertQuestionTypeByEntity(questionTypeEntity: QuestionTypeEntity) {
        questionTypeDao.insertByEntity(questionTypeEntity)
    }

    fun deleteQuestionTypeByEntity(questionTypeEntity: QuestionTypeEntity) {
        questionTypeDao.deleteByEntity(questionTypeEntity)
    }

    fun deleteQuestionTypeByName(name: String) {
        questionTypeDao.deleteByName(name)
    }

    fun getAllQuestionType(): LiveData<List<QuestionTypeEntity>?> {
        return questionTypeDao.selectAll()
    }

    fun getTypeNameById(id: Int): LiveData<String?> {
        return questionTypeDao.selectTypeNameById(id)
    }

    fun updateQuestionType(questionTypeEntity: QuestionTypeEntity) {
        questionTypeDao.update(questionTypeEntity)
    }

    //题目科目的增删查改
    fun insertSubject(userId: String, name: String) {
        subjectDao.insert(userId, name)
    }

    fun insertSubjectByEntity(subjectEntity: SubjectEntity) {
        subjectDao.insertByEntity(subjectEntity)
    }

    fun deleteSubjectByEntity(subjectEntity: SubjectEntity?) {
        subjectDao.deleteByEntity(subjectEntity)
    }

    fun deleteSubjectByName(userId: String, name: String) {
        subjectDao.deleteByName(userId, name)
    }

    fun getAllSubject(userId: String): LiveData<List<SubjectEntity>?> {
        return subjectDao.selectAllByUserId(userId)
    }

    fun getSubjectById(subjectId: Int): LiveData<SubjectEntity?> {
        return subjectDao.selectById(subjectId)
    }

    fun updateSubject(subjectEntity: SubjectEntity?) {
        subjectDao.update(subjectEntity)
    }

    //用户的增删查改
    fun insertUser(userEntity: UserEntity) {
        userDao.insert(userEntity)
    }

    fun deleteUser(userEntity: UserEntity) {
        userDao.delete(userEntity)
    }

    fun getUser(id: String): LiveData<UserEntity?> {
        return userDao.select(id)
    }

    //查询是否有某用户
    fun findUser(id: String): Boolean {
        return userDao.selectUser(id) > 0
    }

    fun updateUser(userEntity: UserEntity) {
        userDao.update(userEntity)
    }

    //错题的增删查改
    fun insertWrongQuestion(questionId: Int, date: Long, score: Float, totalScore: Float, answerPath: String) {
        wrongQuestionDao.insert(questionId, date, score, totalScore, answerPath)
    }

    fun deleteWrongQuestionByEntity(wrongQuestionEntity: WrongQuestionEntity) {
        wrongQuestionDao.deleteByEntity(wrongQuestionEntity)
    }

    fun deleteWrongQuestionByQuestion(questionId: Int) {
        wrongQuestionDao.deleteByQuestion(questionId)
    }

    fun deleteAllWrongQuestion() {
        wrongQuestionDao.deleteAll()
    }

    fun getAllWrongQuestion(): LiveData<List<WrongQuestionEntity>?> {
        return wrongQuestionDao.selectAll()
    }

    fun getWrongQuestionByQuestion(questionId: Int): LiveData<List<WrongQuestionEntity>?> {
        return wrongQuestionDao.selectByQuestion(questionId)
    }

    fun getWrongQuestionInDate(startDate: Long, endDate: Long): LiveData<List<WrongQuestionEntity>?> {
        return wrongQuestionDao.selectInDate(startDate, endDate)
    }

    fun getWrongQuestionInDateAndQuestion(questionId: Int, startDate: Long, endDate: Long): LiveData<List<WrongQuestionEntity>?> {
        return wrongQuestionDao.selectInDateAndQuestion(questionId, startDate, endDate)
    }

    fun getWrongQuestionBeanByUserId(userId: String): LiveData<List<WrongQuestionBean>?> {
        return wrongQuestionDao.selectWrongQuestionBeanByUserId(userId)
    }

    fun getWrongQuestionBeanInSetIdAndInDate(setId: Int, startDate: Long, endDate: Long): LiveData<List<WrongQuestionBean>?> {
        return wrongQuestionDao.selectWrongQuestionBeanInSetIdAndInDate(setId, startDate, endDate)
    }

    fun getWrongQuestionBeanInSubjectIdAndInDate(subjectId: Int, startDate: Long, endDate: Long): LiveData<List<WrongQuestionBean>?> {
        return wrongQuestionDao.selectWrongQuestionBeanInSubjectIdAndInDate(subjectId, startDate, endDate)
    }

    fun getWrongQuestionBeanInDate(startDate: Long, endDate: Long): LiveData<List<WrongQuestionBean>?> {
        return wrongQuestionDao.selectWrongQuestionBeanInDate(startDate, endDate)
    }

    fun getWrongQuestionBeanByQuestionId(questionId: Int): LiveData<List<WrongQuestionBean>?> {
        return wrongQuestionDao.selectWrongQuestionBeanByQuestionId(questionId)
    }

//    fun getWrongQuestionByRight(isRight: Boolean): LiveData<List<WrongQuestionEntity>?> {
//        return wrongQuestionDao.selectByRight(isRight)
//    }

    fun updateWrongQuestionByEntity(wrongQuestionEntity: WrongQuestionEntity) {
        wrongQuestionDao.updateByEntity(wrongQuestionEntity)
    }

//    //因为题目的熟悉程度需要经常更新，所以有一个更新熟悉程度的sql
//    fun updateQuestionFamiliarity(id: Int, familiarity: Float) {
//        wrongQuestionDao.updateFamiliarity(id, familiarity)
//    }

    fun insertQuestionInfo(questionId: Int, familiarity: Float) {
        questionInfoDao.insert(questionId, familiarity, Date().time)
    }

    fun deleteQuestionInfo(questionInfoEntity: QuestionInfoEntity) {
        questionInfoDao.delete(questionInfoEntity)
    }

    fun getQuestionInfoByQuestionId(questionId: Int): LiveData<List<QuestionInfoEntity>?> {
        return questionInfoDao.select(questionId)
    }

    fun getAllQuestionInfo(): LiveData<List<QuestionInfoEntity>?> {
        return questionInfoDao.selectAll()
    }

    init {
        val database = MyDatabase.getDatabase(context)
        appConfigDao = database.appConfigDao
        questionDao = database.questionDao
        questionSetDao = database.questionSetDao
        questionTypeDao = database.questionTypeDao
        subjectDao = database.subjectDao
        userDao = database.userDao
        wrongQuestionDao = database.wrongQuestionDao
        questionInfoDao = database.questionInfoDao
    }
}